package com.haifeng.questionbankcrud.util;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;


public class DBUtils {
    //1.定义成员变量 DataSource
    private static DataSource ds;

    static {
        try {
//
//            //1.加载配置文件
//            Properties pro = new Properties();
//            //使用ClassLoader加载配置文件，获取字节输入流
//            InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
//            pro.load(is);
//            System.out.println(pro.toString());
//            //2.获取DataSource
//            ds =DruidDataSourceFactory.createDataSource(pro);
//            System.out.println(ds);
            Properties pros = new Properties();
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
            pros.load(is);
            ds = DruidDataSourceFactory.createDataSource(pros);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt, Connection conn) {

        close(null, stmt, conn);
    }


    public static void close(ResultSet rs, Statement stmt, Connection conn) {


        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取连接池方法
     */

    public static DataSource getDataSource() {
        return ds;
    }


    public static void main(String[] args) throws Exception {
//
//        Properties pros = new Properties();
//        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
//        pros.load(is);
//        ds = DruidDataSourceFactory.createDataSource(pros);
        Connection connection = getConnection();
        System.out.println(connection);
        connection.close();
    }
}
